<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,nginx," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="一． Nginx简介Nginx 是一个开源的高性能的HTTP和反向代理服务器，用于实现资源缓存、web server负载均衡等功能，其特点是占有内存少，并发能力强。使用nginx网站用户有：百度、京东、新浪、网易、腾讯、淘宝等。是目前最流行的反向代理服务器之一。Nginx反向代理实现Tomcat集群服务器的负载均衡二． Tomcat简介Tomcat是一个免费的开源的纯JAVA开发的Web 应用服务">
<meta property="og:type" content="article">
<meta property="og:title" content="nginx做负载均衡">
<meta property="og:url" content="http://yoursite.com/2017/04/17/nginx做负载均衡/index.html">
<meta property="og:site_name" content="起今知行 | 思考者">
<meta property="og:description" content="一． Nginx简介Nginx 是一个开源的高性能的HTTP和反向代理服务器，用于实现资源缓存、web server负载均衡等功能，其特点是占有内存少，并发能力强。使用nginx网站用户有：百度、京东、新浪、网易、腾讯、淘宝等。是目前最流行的反向代理服务器之一。Nginx反向代理实现Tomcat集群服务器的负载均衡二． Tomcat简介Tomcat是一个免费的开源的纯JAVA开发的Web 应用服务">
<meta property="og:updated_time" content="2017-04-17T15:49:25.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="nginx做负载均衡">
<meta name="twitter:description" content="一． Nginx简介Nginx 是一个开源的高性能的HTTP和反向代理服务器，用于实现资源缓存、web server负载均衡等功能，其特点是占有内存少，并发能力强。使用nginx网站用户有：百度、京东、新浪、网易、腾讯、淘宝等。是目前最流行的反向代理服务器之一。Nginx反向代理实现Tomcat集群服务器的负载均衡二． Tomcat简介Tomcat是一个免费的开源的纯JAVA开发的Web 应用服务">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/04/17/nginx做负载均衡/"/>





  <title> nginx做负载均衡 | 起今知行 | 思考者 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">起今知行 | 思考者</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">自我管理，知识管理，时间管理，阅读</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/04/17/nginx做负载均衡/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Winsion">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="起今知行 | 思考者">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                nginx做负载均衡
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-17T22:22:22+08:00">
                2017-04-17
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/04/17/nginx做负载均衡/" class="leancloud_visitors" data-flag-title="nginx做负载均衡">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计</span>
                
                <span title="字数统计">
                  1,971字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长</span>
                
                <span title="阅读时长">
                  7分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>一． Nginx简介<br>Nginx 是一个开源的高性能的HTTP和反向代理服务器，用于实现资源缓存、web server负载均衡等功能，其特点是占有内存少，并发能力强。使用nginx网站用户有：百度、京东、新浪、网易、腾讯、淘宝等。是目前最流行的反向代理服务器之一。<br>Nginx反向代理实现Tomcat集群服务器的负载均衡<br>二． Tomcat简介<br>Tomcat是一个免费的开源的纯JAVA开发的Web 应用服务器，可以充当轻量级JAVAEE项目的应用服务器，它还是一个运行Servlet和JSP的web容器。<br>三． 为什么要配置服务器集群<br><a id="more"></a><br>服务器集群：是指将很多服务器集中起来一起进行同一种服务，在客户端看来就象是只有一个服务器。 集群可以利用多个计算机进行并行计算从而获得很高的计算速度，也可以用多个计算机做备份，从而使得任何一个机器坏了整个系统还是能正常运行。<br>集群目的：一方面，对于对于日访问量或者并发访问量十分巨大的网站来说，如果只部署一台服务性能十分低下，极有可能对暴风雨般的请求(2016年双十一天猫淘宝几十万的峰值并发请求)招架不住而随时被挂掉，对企业来造成重大损失。有必要多台服务器来分担这种并发请求的压力。另一方面，群集化操作可以减少单点故障数量，就算一台服务器出现了故障，其他服务器正常运行，保证企业的日常运作不受影响，这是非常有必要的事情。并且实现了群集化资源的高可用性。<br>四． 负载均衡<br>对于集群来说，负载均衡意味着当反向代理服务Nginx接受到用户发起的请求后，会把请求按照权重均分到不同的集群服务器上，尽可能让每个服武器均摊请求，减少服务器的压力，提高性能，防止由于高并发导致的服务器宕机或者瘫痪等。<br>应用架构：<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>准备工作：<br>说明：（1）测试环境为windows<br>（2）由于tomcat需要jdk，因此需要安装jdk并配置环境变量<br>（3）下载Nginx并解压(Nginx下载地址：<a href="http://nginx.org" target="_blank" rel="external">http://nginx.org</a>)<br>（4）下载Tomcat (Tomcat下载地址: <a href="http://tomcat.apache.org/download-70.cgi" target="_blank" rel="external">http://tomcat.apache.org/download-70.cgi</a>)<br>（5）准备使用两个tomcat服务器，一个Nginx服务器<br>（6）同一个测试web项目(只包含一个jsp页面)打成war包，分别放在tomcat1和tomcat2的webapps目录下<br>服务器名称    测试版本    测试IP<br>Nginx    Nginx-1.11.13    127.0.0.1:80(默认端口)<br>Tomcat1    7.0+    127.0.0.1:8080<br>Tomcat2    7.0+    127.0.0.1:8090<br>主要内容<br>一．搭建Nginx服务器<br>将下载好的Nginx服务器压缩包放到任意盘（比如D盘）进行解压，解压后目录结构为：图（1）<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>成功。<br>此时：在浏览器中输入本机环回地址测试：<a href="http://127.0.0.1" target="_blank" rel="external">http://127.0.0.1</a><br>若出现图（2）,则说明nginx启动成功，服务器正常运行。<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>注意：由于nginx的默认端口为80，因此要确保本机没有其他应用程序占用该端口。<br>至此我们可以进行下一步工作<br>一．搭建Tomcat服务器<br>在搭建Tomcat服务器前，首先需要在安装jdk，因为Tomcat是java写的，而java运行需要jdk。该步骤不是本文讨论的重点，略去。<br>安装好jdk后，需要将Tomcat服务器压缩文件解压两份，分别取名为Tomcat1和Tomcat2。<br>如图（3）tomcat集群服务器所示：<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>在真实环境中，该服务器可以安装到不同的主机中。<br>其中每个服务器目录结构为：<br>图（4）<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>在图（4）的Conf文件夹下面的配置文件server.xml需要将两个tomcat服务的端口改为本机唯一。（若是不同主机则不用修改，默认端口为8080）<br>将tomcat1的server.xml中的服务端口，连接器端口不动（默认）<br>将tomcat2的server.xml中的服务端口改为8006，连接器端口改为依次8090，8010<br>修改server.xml的文件位置为第22行，第70行，第91行：修改后的效果图（5）为：<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>以上步骤完成即可进行下一步<br>一．准备测试项目<br>准备同一个测试web项目，该项目只有一个index.jsp文件。只是在该文件中写一段分别代表两个不同服务器的文字，以示区别：<br>在准备放入tomcat1的项目的index.jsp中写入：“这是四川展谊科技，我部署在tomcat1中！”<br>在准备放入tomcat2的项目的index.jsp中写入：“这是四川展谊科技，我部署在tomcat2中！”<br>每个项目的目录内部结构为：图（6）所示：<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>紧接着把项目打成war包。然后把项目分别复制到两个tomcat对应的wabapps文件夹（见图4）下面。<br>然后分别在两个tomcat图（4）中的bin文件夹找到startup.bat批处理文件，双击启动服务器。<br>接下来主要工作来了<br>一．Nginx配置负载均衡<br>在图（1）的Nginx的conf文件夹下面找到nginx.conf文件，打开并在该文件的htpp指令模块中添加负载均衡指令（具体添加位置见下图（7）的红色标注区域34行和46行）<br>ont-size:9.0000pt;mso-font-kerning:1.0000pt;” &gt;每个项目的目录内部结构为：图（6）所示：<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>在红色区域添第34行和第46行添加如下命令：<br>第34行红色区添加命令如下：<br>upstream lero{ #其中lero命名可以自定义，但要满足基本的命名规则<br>server 127.0.0.1:8080; #tomcat1服务器的地址<br>server 127.0.0.1:8090; #tomcat2服务器的地址<br>}<br>第46行红色区添加命令如下：<br>proxy_pass <a href="http://lero" target="_blank" rel="external">http://lero</a>; #配置反向代理指向位置<br>完整的配置见下图（8）<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>一．启动服务器<br>修改配置文件后，需要重新启动nginx服务<br>首先在dos命令窗口定位到nginx服务器安装目录（比如：f:nginx-1.11.13）<br>然后输入重启命令为：nginx -s reload（若这种方法无效，建议强行结束进程）<br>如下图（9）：<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>重启tomcat1，tomcat2服务器（点击shutdown.bat批处理文件后，重新点击startup.bat批处理文件即可实现重启），然后在浏览器地址栏输入127.0.0.1/www.sczhanyi.com/<br>访问第一次效果图（10）：<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>访问第二次效果图（11）<br>Nginx反向代理实现Tomcat集群服务器的负载均衡</p>
<p>访问第三次又会把请求发给tomcat1,访问第四次又会把请求发给tomcat2…<br>到此，已实现了nginx反向代理实现tomcat集群服务器的负载均衡配置。每次访问都会轮换切换服务器,把请求分发给不同的服务器！</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/nginx/" rel="tag"># nginx</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/04/17/Linux上搭建FTP服务器/" rel="next" title="Linux上搭建FTP服务器">
                <i class="fa fa-chevron-left"></i> Linux上搭建FTP服务器
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/04/17/FTP上传下载/" rel="prev" title="FTP上传下载">
                FTP上传下载 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="Winsion" />
          <p class="site-author-name" itemprop="name">Winsion</p>
           
              <p class="site-description motion-element" itemprop="description">知识管理，时间管理，自我管理，阅读，语音写作，思维导图，Wiz，TimeMeter</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/winsions" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://coding.net/u/winsions" target="_blank" title="Coding">
                  
                    <i class="fa fa-fw fa-coding"></i>
                  
                  Coding
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/winsions" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  微博
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.douban.com/people/winsions" target="_blank" title="豆瓣">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  豆瓣
                </a>
              </span>
            
          
        </div>

        
        

        
        

        
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=436514312&auto=1&height=66"></iframe>


      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Winsion</span>
</div>


<div >
 <br/>
 <br/>
<script type="text/javascript" src="http://tajs.qq.com/stats?sId=61514183" charset="UTF-8"></script>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("aR58NiUI6UxE1EeSHEMgVuI8-gzGzoHsz", "Tu5BQCGEuL0X0IchB5aYRdxk");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  


<a href="https://github.com/winsions"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/e7bbb0521b397edbd5fe43e7f760759336b5e05f/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f677265656e5f3030373230302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_green_007200.png"></a></html>
